
import ExcelTable from '@/components/exportExcel'
import { ActionType, ProFormInstance } from '@ant-design/pro-components'
import {Button, Drawer, Modal, Form, Input, Flex, Tree,Radio,message,Spin} from 'antd'
import {useRef, useState,useEffect} from 'react'
import {useNavigate,useLocation} from 'react-router-dom'
import type { RadioChangeEvent } from 'antd';
import { getGroupMember } from '@/apis/accessManagement/group'
import { muteGroupMember } from '@/apis/accessManagement/group'
import { cancelMuteGroupMember } from '@/apis/accessManagement/group'
import { kickGroupMember } from '@/apis/accessManagement/group'
import dayjs from 'dayjs';

const GroupDetail: React.FC = () => {
    useRef<ActionType>()
    useRef<ProFormInstance>()
    const { TextArea } = Input
    const navigate = useNavigate()
    const actionRef = useRef()
    const location = useLocation()
    const query = new URLSearchParams(location.search);
    const groupID = query.get('groupID');
    const [loading, setLoading] = useState(false); // 加载状态
    // const [tableItem, setTableItem] = useState()
    const [form] = Form.useForm()
    const [memberRoleDraw, setMemberRoleDraw] = useState(false)
    const [handleUserId, setHandleUserId] = useState('')
    const [muteMemberDraw, setMuteMemberDraw] = useState(false)
    const [kickMemberDraw, setKickMemberDraw] = useState(false)
    const [memberRoleRadio, setMemberRoleRadio] = useState(0);
    const [muteAuth, setMuteAuth] = useState(false)
    const [removeAuth, setRemoveAuth] = useState(false)
    const onRadioChange = (e: RadioChangeEvent) => {
        console.log('radio checked', e.target.value)
        setMemberRoleRadio(e.target.value)
      };
    const [messageApi, contextHolder] = message.useMessage();

    function subChangeRole(item: any) {
        // sub fn add here
        form.resetFields()
        setMemberRoleDraw(false)
        messageApi.open({
            type: 'success',
            content: '提交成功demo',
            duration: 4,
        });
    }

    function onCloseDrawer() {
        form.resetFields()
        setMemberRoleDraw(false)
    }

    function onCloseMuteDrawer() {
        form.resetFields()
        setMuteMemberDraw(false)
    }

    function onCloseKickDrawer() {
        form.resetFields()
        setKickMemberDraw(false)
    }

    function switchMute(record:any) {
        console.log(record.userID)
        setHandleUserId(record.userID)
        record.muteEndTime?subCancelMute(record):subMute(record)
    }

        // 原模式：输入时间后提交 
    // const showMuteDraw = (record:any) => {
        // 原模式：输入时间后提交
        // setHandleUserId(record.userID)
        // record.muteEndTime?
        // Modal.warning({
        //     title: '提示',
        //     content: '确定解除禁言该用户吗?',
        //     okText: '确定',
        //     okCancel: true,
        //     onOk() {
        //         subCancelMute()
        //     }
        // }):setMuteMemberDraw(true)
    // }

    // 提交禁言
    const subMute = async (record:any) => {
        setLoading(true)
        try {
            const response = await muteGroupMember({
                groupID: groupID,
                userID:record.userID,
                // mutedSeconds:parseInt(form.getFieldValue('mute')),
                mutedSeconds:10000,
            });
            if (response || response.data) {
                // const { errCode, errMsg } = response;
                console.log(response)
                if (response?.errCode === 0) {
                    message.success('禁言提交成功');
                    onCloseMuteDrawer()
                    actionRef.current?.reload()
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // 提交解除禁言用户
    const subCancelMute = async (record:any) => {
        setLoading(true)
        try {
            const response = await cancelMuteGroupMember({
                groupID: groupID,
                userID:record.userID,
            });
            if (response || response.data) {
                // const { errCode, errMsg } = response;
                console.log(response)
                if (response?.errCode === 0) {
                    message.success('解除禁言成功');
                    actionRef.current?.reload()
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    const showKickDraw = (record:any) => {
        console.log(record)
        setKickMemberDraw(true)
        setHandleUserId(record.userID)
    }

    // 移除成员
    const subKick = async () => {
        setLoading(true)
        try {
            const kickIds: string[] = [handleUserId];
            const response = await kickGroupMember({
                groupID: groupID,
                kickedUserIDs:kickIds,
                reson:form.getFieldValue('kick')
            });
            if (response || response.data) {
                // const { errCode, errMsg } = response;
                console.log(response)
                if (response?.errCode === 0) {
                    message.success('移除成员成功');
                    setKickMemberDraw(false)
                    actionRef.current?.reloadAndRest()
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    useEffect(() => {
        const processAuthData = (authData: any[]) => {
            console.log(authData)
            // 递归
            const traverse = (nodes: any[]) => {
                for (const node of nodes) {
                    if (node.name === '群组' && node.children && node.children.length > 0) {
                        traverse(node.children);
                    }
                    if (node.name === '群组成员' && node.children && node.children.length > 0) {
                        traverse(node.children);
                    }
                    // 检查子节点的 name
                    if (node.name === "群成员禁言") {
                        setMuteAuth(true)
                    }
                    if (node.name === "群成员移除") {
                        setRemoveAuth(true)
                    }
                    // 如果两个权限都已经找到，提前结束递归
                    if (muteAuth) {
                        return;
                    }
                    // 如果当前节点有子节点，递归处理子节点
                    if (node.children && node.children.length > 0) {
                        traverse(node.children);
                    }
                }
            };
            traverse(authData);
            return { muteAuth};
        };
        const checkRouters = setInterval(() => {
            const authData = window.routers?.routes?.[1]?.children || [];
            if (authData.length > 0) {
                clearInterval(checkRouters); // 停止检查
                processAuthData(authData); // 执行逻辑
            }
        }, 200);
        return () => clearInterval(checkRouters); // 清理定时器
    },[])

    return (
        <>
            {contextHolder}
            <Spin spinning={loading} fullscreen size='large'/>
            <ExcelTable
                actionRef={actionRef}
                requestFn={ params => {
                    const { pageNum,pageSize,userID='', ...newParams } = params; //
                    console.log(groupID)
                    const data = getGroupMember({
                        ...newParams,
                        pagination: {pageNumber:pageNum,showNumber:pageSize}, 
                        keyword: userID,
                        groupID:groupID
                    })
                    return data
                }}
                rowSelection={false}
                toolBarRenderFn={() => [
                    // <Button key="add" onClick={() => {
                    //     navigate('/group/groupManage/addGroup?state=1')
                    // }}>新增群组</Button>
                ]}
                columns={[
                    {
                        title: '序号',
                        valueType: 'index',
                        hideInSearch: true
                    },
                    {
                        title: '用户ID',
                        dataIndex: 'userID',
                    },
                    {
                        title: '用户昵称',
                        dataIndex: 'nickname',
                        hideInSearch: true,
                        render: (_, record) => record.nickname || '暂无数据',
                    },
                    {
                        title: '加入时间',
                        dataIndex: 'joinTime',
                        hideInSearch: true,
                        render: (_, record) =>
                            record?.joinTime
                              ? dayjs(record?.joinTime).format('YYYY-MM-DD HH:mm:ss')
                              : '暂无数据',
                    },
                    {
                        title: '成员角色',
                        dataIndex: 'roleLevel',
                        hideInSearch: true,
                        render: (_, record) => record.roleLevel === 100?'群主':record.roleLevel === 60?'管理员':'普通成员'
                    },
                    {
                        title: '加群来源',
                        dataIndex: 'joinSource',
                        hideInSearch: true,
                        render: (_, record) => record.joinSource === 1?'管理员邀请':record.joinSource === 2?'群成员邀请':record.joinSource === 3?'搜索加入':'扫码加入'
                    },
                    {
                        title: '操作人ID',
                        dataIndex: 'handleUser',
                        hideInSearch: true,
                        render: (_, record) => record.operatorUserID || '暂无数据',
                    },
                    {
                        title: '操作',
                        key: 'option',
                        valueType: 'option',
                        render: (_, record) => [
                            // <a key="update" onClick={() => {setMemberRoleDraw(true)}}>设置群身份</a>,    
                            // <a key="disabled" onClick={() => {showMuteDraw(record)}}>{record.muteEndTime?'解除禁言':'禁言'}</a>,    
                            muteAuth && (<a key="disabled" onClick={() => {
                                const muteText = record.muteEndTime?'解除禁言':'禁言'
                                Modal.warning({
                                    title: '提示',
                                    content: `确定${muteText}该用户吗?`,
                                    okText: '确定',
                                    okCancel: true,
                                    onOk() {
                                        switchMute(record)
                                    }
                                })
                            }}>{record.muteEndTime?'解除禁言':'禁言'}</a>),    
                            // <a key="disabled" onClick={() => {
                            //     const forbiddenText = record.sendStatus === '正常' ? '禁言' : '解禁'
                            //     Modal.warning({
                            //         title: '提示',
                            //         content: `确定${forbiddenText}该用户吗?`,
                            //         okText: '确定',
                            //         okCancel: true,
                            //         onOk() {
                            //             console.log('Confirmed:onOk ')
                            //         }
                            //     })
                            // }}>{record.sendStatus === '正常'?'禁言':'解禁'}</a>,
                            removeAuth && (<a key="kick" onClick={() => {showKickDraw(record)}}>移除</a>)
                        ]
                    }
                ]}/>
            <Drawer title="设置群身份" onClose={onCloseDrawer} open={memberRoleDraw}>
                <Form form={form} onFinish={subChangeRole}>
                    <Form.Item label="设置群身份" name="usetype" rules={[{ required: true ,message: '请设置群身份！'}]}>
                        <Radio.Group onChange={onRadioChange} value={memberRoleRadio}>
                        <Radio value={1}>群主</Radio>
                        <Radio value={2}>管理员</Radio>
                        <Radio value={3}>成员</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item>
                        <Flex justify='center' align='center'>
                            <Button type="primary" htmlType="submit">提交</Button>
                            <Button style={{marginLeft: 10}} onClick={onCloseDrawer}>返回</Button>
                        </Flex>
                    </Form.Item>
                </Form>
            </Drawer>
            <Drawer title="确定禁言此用户吗？" onClose={onCloseMuteDrawer} open={muteMemberDraw}>
                <Form form={form} onFinish={subMute}>
                    <Form.Item label="禁言时间" name="mute" rules={[{required: true, message: '请输入禁言时间'},{ max: 100, message: '最多输入100个字符' }]}>
                        <Input allowClear type="number" maxLength={6} placeholder={'请输入禁言时间(秒)'}/>
                    </Form.Item>
                    <Form.Item>
                        <Flex justify='center' align='center'>
                            <Button type="primary" htmlType="submit">提交</Button>
                            <Button style={{marginLeft: 10}} onClick={onCloseMuteDrawer}>返回</Button>
                        </Flex>
                    </Form.Item>
                </Form>
            </Drawer>
            <Drawer title="确定移除此成员吗？" onClose={onCloseKickDrawer} open={kickMemberDraw}>
                <Form form={form} onFinish={subKick}>
                    <Form.Item label="移除原因" name="kick">
                        <TextArea rows={4} maxLength={100} placeholder={'请输入移除原因(最多输入100个字符)'}/>
                    </Form.Item>
                    <Form.Item>
                        <Flex justify='center' align='center'>
                            <Button type="primary" htmlType="submit">提交</Button>
                            <Button style={{marginLeft: 10}} onClick={onCloseKickDrawer}>返回</Button>
                        </Flex>
                    </Form.Item>
                </Form>
            </Drawer>
        </>
    )
}

export default GroupDetail
